import React, { useState, useEffect } from 'react'
import { http, UdModalForm, validators } from '@/lib'
import apis from '@/apis/UserManagement'
import { Select, Input, TreeSelect, Spin, Icon } from 'antd'
import EnableRadioGroup from '../EnableRadioGroup'
import NotFoundContent from '@components/NotFoundContent'
import _ from 'lodash'

const Option = Select.Option

export default function UpdateModalContent(props) {
  const { data, values, rowId, areaSelectChangeHandle, areaList = [], ...reset } = props
  const formLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
  }
  let fetchTimer
  const [customerList, setCustomerList] = useState([])
  // const [areaList, setAreaList] = useState([])
  const [userList, setUserList] = useState([])
  const [querying, setQuerying] = useState(false)

  useEffect(() => {
    // getModalSelectData()
    if (rowId) {
      const { belongAreaCode } = data
      const { agentName: { key, lable } } = values
      // getModalSelectData({ organization: belongAreaCode })
      setCustomerList([{ value: key, title: lable }])
    }
    return () => {
      setCustomerList([])
    }
  }, [props.rowId])

  const getModalSelectData = (params?) => {
    const rqParams = params || {}
    http.post(apis.DealerAccountMessage, rqParams).then(res => {
      const data = res.data
      if (params) {
        const { businessPerson = [] } = data
        const userList = businessPerson.map(({ id: value, realname: title }) => ({ value, title }))
        setUserList(userList)
      } else {
        // const { OrgData = [] } = data
        // const { nodes: areaList } = frormatTreeData([OrgData])
        // console.log('areaList', areaList)
        // setAreaList(areaList)
      }
    })
  }

  const getCustomerListByName = (name) => {
    setQuerying(true)
    setCustomerList([])
    http.post(apis.DealerAccountMessage, { customerName: name }).then(res => {
      const { agentMdm = [] } = res.data
      const customerList = agentMdm.map(item => ({ value: item?.sapCustomerCode, title: item?.customerName }))
      setCustomerList(customerList)
    }).finally(() => setQuerying(false))
  }

  /* const frormatTreeData = (datas) => {
    let nodes: any = []
    const loopFormat = (datas) => {
      if (!_.isArray(datas) || datas.length == 0) {
        return []
      }
      let treeNodes = []
      datas.map(item => {
        const { children, name: title, id: key, code: value } = item
        let treeNode = { key, value, title, children }
        treeNode.children = loopFormat(children)
        treeNodes.push(treeNode)
      })
      return treeNodes
    }
    nodes = loopFormat(datas)
    return { nodes }
  } */

  const findAreaTreeInfo = (datas, val, findKey = 'value', children = 'children') => {
    let info = {}
    const loop = (datas) => {
      if (!_.isArray(datas) || datas.length == 0) {
        return
      }
      for (const key in datas) {
        if (datas.hasOwnProperty(key)) {
          console.log('findKey', datas[key][findKey])
          if (val == datas[key][findKey]) {
            info = datas[key]
            return
          }
          datas[key][children] && loop(datas[key][children])
        }
      }
    }
    loop(datas)
    return info
  }

  const fetchCustomer = (val) => {
    if (!val) {
      return
    }
    if (fetchTimer) {
      clearTimeout(fetchTimer)
    }
    fetchTimer = setTimeout(() => {
      getCustomerListByName(val)
      fetchTimer = null
    }, 500)
  }

  const customerNameChange = (val, props) => {
    const { form } = props
    let key = undefined
    if (val) {
      // const { lable } = val
      key = val.key
    }
    form.setFieldsValue({ agentName: val, agentCode: key })
  }

  const areaSelectChange = (val, props) => {
    const { form } = props
    if (val) {
      const { value } = val
      // 获取选择区域的id
      const info: any = findAreaTreeInfo(areaList, value)
      const { id } = info
      // 保存选择的管理区域id
      // modalChooseAreaId = id
      areaSelectChangeHandle && areaSelectChangeHandle(id)
      getModalSelectData({ organization: value })
    }
    form.setFieldsValue({ userId: undefined })
  }
  const customerSelectScroll = (e) => {
    e.persist()
    const { target } = e
    if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
      // const { scrollPage } = this.state
      // const nextScrollPage = scrollPage + 1
      console.log(121)
    }
  }

  return (
    <UdModalForm {...reset} items={[
      {
        id: 'agentName', label: '客户名称', ...formLayout, rules: [validators.required], render: (props) => (
          <Select
            getPopupContainer={triggerNode => triggerNode.parentElement}
            optionFilterProp="children"
            labelInValue={true}
            showSearch={true}
            notFoundContent={querying ? <Spin size="small" /> : <NotFoundContent />}
            onSearch={fetchCustomer}
            onChange={(val) => customerNameChange(val, props)}
            // onPopupScroll={customerSelectScroll}
            placeholder='请输入客户名称搜索'
            suffixIcon={<Icon type='search' />}
            className='ud-search-select'
            disabled={rowId ? true : false}
          >
            {customerList.map(({ value, title }) => <Option key={value} value={value}>{title}</Option>)}
          </Select>
        )
      },
      {
        id: 'agentCode', label: '客户编码', ...formLayout, rules: [validators.required], render: ({ form }) => {
          return <Input disabled />
        }
      },
      {
        id: 'accountType', label: '用户类型', ...formLayout, rules: [validators.required], render:
          <Select disabled={true}>
            <Option value='1'>经销商</Option>
          </Select>
      },
      {
        id: 'roleId', label: '角色', ...formLayout, rules: [validators.required], render:
          <Select mode='multiple' disabled={true}>
            <Option value='1'>主账号</Option>
          </Select>
      },
      { id: 'userName', label: '联系人', ...formLayout, rules: [validators.required, validators.max(10), validators.userName] },
      { id: 'phone', label: '联系电话', ...formLayout, rules: [validators.required, validators.phoneCommonly], decoratorOptions: { validateFirst: true } },
      /* {
        id: 'belongAreaCode', label: '所属管理区域', ...formLayout, labelCol: { span: 5 }, wrapperCol: { span: 18 }, rules: [validators.required], render: (props) => (
          <TreeSelect treeNodeFilterProp="title" labelInValue={true} getPopupContainer={triggerNode => triggerNode.parentElement} showSearch={true} treeData={areaList} onChange={(val) => areaSelectChange(val, props)} />
        )
      },
      {
        id: 'userId', label: '关联业务员', ...formLayout, rules: [validators.required], render:
          <Select getPopupContainer={triggerNode => triggerNode.parentElement}>
            {userList.map(({ value, title }) => <Option key={value} value={value}>{title}</Option>)}
          </Select>
      }, */
      // { id: 'isValid', label: '状态', ...formLayout, rules: [validators.required], render: <EnableRadioGroup /> },
    ]} values={values} />
  )
}